import Ember from 'ember';
import BaseItem from '../ui/base-ui-item';
import Changeset from 'ember-changeset';
import evaValidations from '../../validations/eva';
import lookupValidator from 'ember-changeset-validations';

export default BaseItem.extend(evaValidations, {
    globalCurStatus: Ember.inject.service('current-status'),
    changeFlag: 0,
    difference:false,
    hasChoosed: true,
    modelID: "",
    answerId: "",
    resultShow: true,
    constants: Constants,
    statusService: Ember.inject.service("current-status"),
    store: Ember.inject.service("store"),
    dateService: Ember.inject.service("date-service"),
    pathConfiger: Ember.inject.service("path-configer"),
    realAnswerList: new Ember.A(),
    didInsertElement: function() {
        var _self = this;
        console.log("scores is what", this.get("evaluate.scores"));
        if (this.get("evaluate.model").get("type")) {
            var modelTypeCode = this.get("evaluate").get('model.type').get("typecode");
            if (modelTypeCode == "evaluateTypeByScore") {
                console.log("if this get modelID", this.get("evaluate").get('model.type'));
                this.set("resultShow", false);
            }
            if (modelTypeCode == "evaluateTypeByItem") {
                this.set("resultShow", true);
            }
            if (this.get("evaluate.scores")) {
                var filterLevel = {};
                var computedScores = this.get("evaluate.scores");
                console.log("computedScores is", computedScores);
                filterLevel = $.extend({}, {
                    'lowScore@$lte': computedScores
                }, {
                    'highScore@$gte': computedScores
                });
                console.log("filterLevel is", filterLevel);
                this.get("store").query('nursinglevel', {
                    filter: filterLevel
                }).then(function(level) {
                    console.log("level is what", level);
                    level.forEach(function(levelObiect) {
                        var levelName = levelObiect.get("name");
                        console.log("levelName is", levelObiect.get("name"));
                        _self.get("evaluate").set("levelName", levelName);
                        console.log("evaluate levelName", _self.get("evaluate.levelName"));
                    });
                });
            }
        }
        if(this.get("editMode")){
          this.set("difference",true);
        }else {
          this.set("difference",false);
        }
    },
    evaModelObs: function() {
        console.log("evaluate cimpute");
        var model = this.get("evaluate");
        console.log("model evaluate", model);
        if (!model) {
            return null;
        }
        this.set("evaModel", new Changeset(model, lookupValidator(evaValidations), evaValidations));
        this.questionListProcess();
    }.observes("changeFlag").on('init'),

    refreshStaffList: function() {
        var route = App.lookup('route:business.mainpage.eva-question');
        route.refresh();
    },
    detailModify: Ember.computed("addMode", function() {
        var addMode = this.get("addMode");
        if (addMode) {
            return true;
        } else {
            return false;
        }
    }),
    questionListProcess: function() {
        this.set("modelID", this.get("evaModel.model.id"));
        console.log("evaModelid is what", this.get("evaModel.model.id"));
        // if (!this.get("evaModel")) {
        //     return;
        // }
        if (!this.get("modelID")) {
            return;
        }
        var _self = this;
        var realQuestionList = new Ember.A();
        this.set("realQuestionList", realQuestionList);
        var answers = new Ember.A();
        this.set("myAnswer", answers);
        this.get("store").query("evaluateexameranswer", {
            filter: {
                result: {
                    "id": this.get("evaModel").get("id")
                }
            }
        }).then(function(retAnswerList) {
            var index = 0;
            var len = retAnswerList.get("length");
            console.log("sheet len", len);
            console.log("retAnswerList is", retAnswerList);
            retAnswerList.forEach(function(answer) {
                console.log("answer id:" + answer + " and answer.id：" + answer.get("answer.id"));
                answer.set("answerId", answer.get("answer.id"));
                _self.get("myAnswer").pushObject(answer);
                index++;
                if (index >= len) {
                    _self.doQuery();
                }
            });
        });
    },
    doQuery: function() {
        //alert("doQuery");
        var _self = this;
        var filter = {};
        if (this.get('modelID')) {
            filter = $.extend({}, filter, {
                question: {
                    '[model][id]': this.get('modelID')
                }
            });
        }
        //通過question的id去查到对应的answer
        this.get("store").query('evaluateanswer', {
            filter: filter,
        }).then(function(answerList) { //answerList标准答案
            console.log("sheet normal answerList is", answerList);
            var questionOri = null;
            var realIndex = 1;
            var answerFlag = 1;
            var answerIndex = "A";
            var curUser = _self.get("globalCurStatus").getUser();
            _self.get("store").findRecord('user', curUser.get("id")).then(function(user) { //通过创建人id查询createUser
                answerList.forEach(function(answer) { //循环出每一条标准的答案
                    //构造问题
                    var questionReal = answer.get("question"); //循环得到的每一个 问题
                    console.log("questionReal is", questionReal);
                    answer.set("hasSelcted", false);
                    //console.log("realQuestionList isis", _self.get("realQuestionList"));
                    if (!questionOri || questionReal.get("id") !== questionOri.get("id")) {
                        questionOri = questionReal;
                        questionReal.set("realIndex", realIndex);
                        realIndex++;
                        answerFlag = 1;
                        answerIndex = "A";
                        answer.set("answerIndex", answerIndex);
                        console.log("answerIndex", answerIndex);

                        console.log("sheet questionOri is", questionOri);
                        console.log("sheet questionReal is", questionReal);
                        _self.get("realQuestionList").pushObject(questionOri);
                        console.log("realQuestionList isiswhat", _self.get("realQuestionList"));
                        questionReal.set("answerList", new Ember.A());
                        console.log("questionReal id:" + questionReal.get("id") + " and push answer:" + answer.get("id") + " and list size:" + questionReal.get("answerList").get('length'));
                        questionReal.get("answerList").pushObject(answer);
                        questionReal.reopen({
                            curAnswerId: null,
                            curAnswerObs: function() {
                                var _selfReal = this;
                                console.log("curAnswerId is", _selfReal.get("curAnswerId"));
                                this.get("answerList").forEach(function(answer) {
                                    if (answer.get("id") !== _selfReal.get("curAnswerId")) {
                                        answer.set("hasSelcted", false);
                                    } else {
                                        answer.set("hasSelcted", true);
                                        console.log("match answer id is", answer);
                                        questionReal.get("answermodel").set("answerId", answer.get("id"));
                                        questionReal.get("answermodel").set("answertemp", answer);
                                        console.log("answermodel in question after", questionReal.get("answermodel"));
                                    }
                                });
                            }.observes("curAnswerId").on("init"),
                        });

                    } else {
                        console.log("questioniru id:" + questionOri.get("id") + " and push answer:" + answer.get("id"));
                        questionOri.get("answerList").pushObject(answer);
                        if (answerFlag == 1) {
                            answerIndex = "A";
                        }
                        answerFlag++;
                        if (answerFlag == 2) {
                            answerIndex = "B";
                        }
                        if (answerFlag == 3) {
                            answerIndex = "C";
                        }
                        if (answerFlag == 4) {
                            answerIndex = "D";
                        }
                        answer.set("answerIndex", answerIndex);
                    }
                    let answermodel = null;
                    if (!_self.get("id")) {
                        answermodel = _self.get("store").createRecord('evaluateexameranswer', {
                            question: questionReal,
                            answer: null,
                            result: _self.get("evaluate"),
                            createUser: user,
                            lastUpdateUser: user
                        });
                        questionOri.set("answermodel", answermodel);
                    } else {
                        answermodel = _self.get("myAnswer").findBy("answerId", answer.get("id"));
                        if (answermodel) {
                            console.log("answerid get", answer.get("id"));
                            questionOri.set("answermodel", answermodel);
                            questionOri.set("curAnswerId", answermodel.get("answerId"));
                        } else {
                            answermodel = _self.get("store").createRecord('evaluateexameranswer', {
                                question: questionOri,
                                answer: null,
                                result: _self.get("evaluate"),
                                createUser: user,
                                lastUpdateUser: user
                            });
                            questionOri.set("answermodel", answermodel);
                        }
                        console.log("answermodel get", questionOri.get("answermodel"));
                    }
                });
            });
        });
        // this.get("store").query('evaluatequestion', {        //     filter: filter,
        // }).then(function(questionList) {
        //     console.log("questionList is who", questionList);
        //     _self.set('questionList', questionList);
        //     //查询问题
        //     questionList.forEach(function(question) {
        //         console.log("question is who", question);
        //         //_self.set('question', question);
        //         //查询答案
        //         _self.set("answerId", question.get("id"));
        //         _self.get("store").query("evaluateanswer", {
        //             filter: {
        //                 '[question][id]': _self.get('answerId')
        //             },
        //         }).then(function(answerList) {
        //           console.log("answerList is who",answerList);
        //             question.set('answerList', answerList);
        //            answerList.forEach(function(answer){
        //              console.log("answer is who",answer);
        //             // _self.set('answer', answer);
        //            });
        //         });
        //     });
        // });
    },

    actions: {
        search: function() {
            var _self = this;
            this.doQuery();
        },
        invalid() {},
        //修改
        detailModifyClick: function() {
            this.set('detailModify', true);
        },
        //保存按钮
        detailSaveClick: function() {
            var _self = this;
            var evaModel = this.get("evaModel");
            var mainpageController = App.lookup('controller:business.mainpage');
            evaModel.validate().then(function() {
                //alert("save   out");
                if (evaModel.get('errors.length') === 0) {
                  App.lookup('controller:business.mainpage').openPopTip("正在保存");
                    console.log("sheet evaModel is", evaModel);
                    evaModel.save().then(function() {
                        _self.get("realQuestionList").forEach(function(questionReal) {
                            console.log("questionReal is", questionReal);
                            var answermodel = questionReal.get("answermodel");
                            answermodel.set("answer", answermodel.get("answertemp"));
                            console.log("answermodel in save", answermodel);
                            answermodel.save().then(function() {
                                //alert("保存成功");
                                App.lookup('controller:business.mainpage').showPopTip("保存成功");
                            });
                        });
                        if (_self.get('addMode')) {
                            alert("添加");
                            mainpageController.switchMainPage('eva-question', {});
                        }
                        _self.set('detailModify', false);
                    });
                } else {
                    evaModel.set("validFlag", Math.random());
                    alert("校验失败");
                }
                //保存问卷问题和答案
            });
        },
        //取消按钮
        cancelClick: function() {
            var mainpageController = App.lookup('controller:business.mainpage');
            this.set('detailModify', false);
            //alert("详情");
            if (!this.get('addMode')) {
                this.get("evaluate").rollbackAttributes();
                this.set("evaModel", new Changeset(this.get("evaluate"), lookupValidator(evaValidations), evaValidations));
            }
            if (this.get("addMode")) {
                mainpageController.switchMainPage('eva-question', {
                    //flag: 'edit-add'
                });
            }
        },
        //删除按钮
        delById: function(evaluate) {
            //this.set('showpopInvitePassModal', true);
            var _self = this;
            App.lookup('controller:business.mainpage').showConfirm("是否确定删除此基本信息", function() {
                App.lookup('controller:business.mainpage').openPopTip("正在删除");
                evaluate.set("delStatus", 1);
                evaluate.save().then(function() {
                    App.lookup('controller:business.mainpage').showPopTip("删除成功");
                    var mainpageController = App.lookup('controller:business.mainpage');
                    mainpageController.switchMainPage('eva-question');
                });
            });
        },
        changeCreateDateAction(date) {
            var stamp = this.get("dateService").getLastSecondStampOfDay(date);
            this.set("evaModel.createDateTime", stamp);
        },
        //评估人
        selectParent(user) {
            this.get('evaModel').set("user", user);
            this.set("parent", user);
        },
        //模板
        selectModel(model) {
            this.set("model", model);
            this.get('evaModel').set("model", model);
            console.log("evaModel model",this.get('evaModel.model'));
            console.log("sheet id", this.get("model.id"));
            if (!model) {
                return;
            }
            this.set("modelID", model.id);
            var realQuestionList = new Ember.A();
            this.set("realQuestionList", realQuestionList);
            //console.log("realQuestionList is", realQuestionList);
            this.send('search');
            //this.set('modelID', '');
            //this.set("length",this.get("realQuestionList.length"));
        },
        //老人姓名
        selectCustomer(customer) {
            this.get('evaModel').set("customer", customer);
            this.set("evaModel.customer", customer);
        },
        chooseAnswer(answer, question) {
            //alert("curAnswerId");
            if(this.get("detailModify")){
              var curAnswerId = answer.get("id");
              console.log("curAnswerId is:" + curAnswerId);
              question.set("curAnswerId", curAnswerId);
            }
        },
    }
});
